package com.itheima.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.itheima.dto.ArticleConfigDto;
import com.itheima.mapper.ArticleConfigMapper;
import com.itheima.mapper.ArticleContentMapper;
import com.itheima.mapper.ArticleMapper;
import com.itheima.service.ArticleService;
import com.itheima.dto.ArticleDto;
import com.itheima.dto.ArticleSaveDto;
import com.itheima.po.Article;
import com.itheima.po.ArticleConfig;
import com.itheima.po.ArticleContent;
import com.itheima.vo.ArticleConfigVo;
import com.itheima.vo.ArticleVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;

/**
 * @author :wujunjie
 * createTime :2022-12-28 19:15
 * description :
 */
@Service
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private ArticleConfigMapper articleConfigMapper;
    @Autowired
    private ArticleContentMapper articleContentMapper;
    @Override
    public List<ArticleVo> load(String flag,ArticleDto articleDto) {
        if (ObjectUtils.isEmpty(articleDto)){
            throw new RuntimeException("入参不得为空");
        }

        if (articleDto.getSize()==null||articleDto.getTag()==null){
            throw new RuntimeException("每页显示条数和频道数不能为空");
        }


//        LambdaQueryWrapper<Article> lqw = new LambdaQueryWrapper<>();
        MPJLambdaWrapper<Article> lqw=new MPJLambdaWrapper<>();

        if (!"0".equals(articleDto.getMaxBehotTime())&&("loadnew".equals(flag)||"load".equals(flag))){
            Instant instant = Instant.ofEpochMilli(Long.parseLong(articleDto.getMaxBehotTime()));
            LocalDateTime publishTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
            lqw.gt(Article::getPublishTime, publishTime);
        }

        if (!"0".equals(articleDto.getMinBehotTime())&&"loadmore".equals(flag)){
            Instant instant = Instant.ofEpochMilli(Long.parseLong(articleDto.getMinBehotTime()));
            LocalDateTime publishTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
            lqw.lt(Article::getPublishTime, publishTime);
        }

        Integer channelId  = getChannelId(articleDto.getTag());
        if (!ObjectUtils.isEmpty(channelId)){
            lqw.eq(Article::getChannelId,channelId);
        }
        lqw.selectAll(Article.class);
        lqw.leftJoin(ArticleConfig.class,ArticleConfig::getArticleId,Article::getId);
        lqw.eq(ArticleConfig::getIsDown,0);
        lqw.eq(ArticleConfig::getIsDelete,0);
        lqw.orderByDesc(Article::getPublishTime);
        String last="limit "+articleDto.getSize();
        lqw.last(last);

        List<Article> articles = articleMapper.selectList(lqw);

        if (CollectionUtils.isEmpty(articles)){
            return null;
        }
        return BeanUtil.copyToList(articles, ArticleVo.class);
    }

    @Transactional
    @Override
    public Long save(ArticleSaveDto articleSaveDto) {
        if (ObjectUtils.isEmpty(articleSaveDto)){
            throw new RuntimeException("入参不能为空");
        }

        if (ObjectUtils.isEmpty(articleSaveDto.getId())){
            Article article = new Article();
            BeanUtils.copyProperties(articleSaveDto,article);
            article.setFlag(0);
            article.setLikes(0);
            article.setCollection(0);
            article.setComment(0);
            article.setViews(0);
            //todo 加入不可添加的条件判断
            article.setId(IdUtil.getSnowflakeNextId());
            int insertArticle = articleMapper.insert(article);

            ArticleContent articleContent = new ArticleContent();
            articleContent.setId(IdUtil.getSnowflakeNextId());
            articleContent.setArticleId(article.getId());
            articleContent.setContent(articleSaveDto.getContent());
            int insertArticleContent = articleContentMapper.insert(articleContent);

            ArticleConfig articleConfig=new ArticleConfig();
            articleConfig.setId(IdUtil.getSnowflakeNextId());
            articleConfig.setArticleId(article.getId());
            articleConfig.setIsComment(1);
            articleConfig.setIsForward(1);
            articleConfig.setIsDown(0);
            articleConfig.setIsDelete(0);
            int insertArticleConfig = articleConfigMapper.insert(articleConfig);

            if (insertArticle==1&&insertArticleContent==1&&insertArticleConfig==1) {
                return article.getId();
            }
            throw new RuntimeException("新增失败");
        }
        Article articleInDB = articleMapper.selectById(articleSaveDto.getArticleId());
        if (ObjectUtils.isEmpty(articleInDB)){
            throw new RuntimeException("该文章数据为空");
        }
        Article article = new Article();
        BeanUtil.copyProperties(articleSaveDto,article);
        article.setId(articleInDB.getId());
        article.setFlag(articleInDB.getFlag());
        article.setLikes(articleInDB.getLikes());
        article.setCollection(articleInDB.getCollection());
        article.setComment(articleInDB.getComment());
        article.setViews(articleInDB.getViews());
        int articleUpdate = articleMapper.updateById(article);
        MPJLambdaWrapper<ArticleContent> contentWrapper=new MPJLambdaWrapper<>();
        contentWrapper.eq(ArticleContent::getArticleId, article.getId());
        ArticleContent articleContentInDB = articleContentMapper.selectOne(contentWrapper);
        if (ObjectUtils.isEmpty(articleContentInDB)){
            throw new RuntimeException("该文章内容数据为空");
        }
        articleContentInDB.setContent(articleSaveDto.getContent());
        int contentUpdate = articleContentMapper.updateById(articleContentInDB);
        if (articleUpdate==1&&contentUpdate==1){
            return article.getId();
        }
        throw new RuntimeException("更新失败");
        //todo 文章上传成功后需要生成静态页面
    }

    @Override
    public ArticleConfigVo selectConfig(ArticleConfigDto articleConfigDto) {
        MPJLambdaWrapper<Article> selectWrapper=new MPJLambdaWrapper<>();
        selectWrapper.eq(Article::getId, articleConfigDto.getArticleId());
        selectWrapper.eq(Article::getAuthorId, articleConfigDto.getAuthorId());

        Article article = articleMapper.selectOne(selectWrapper);
        if (ObjectUtils.isEmpty(article)){
            throw new RuntimeException("该文章不存在");
        }

        MPJLambdaWrapper<ArticleConfig> configWrapper=new MPJLambdaWrapper<>();
        configWrapper.eq(ArticleConfig::getArticleId, articleConfigDto.getArticleId());
        ArticleConfig articleConfigInDB = articleConfigMapper.selectOne(configWrapper);
        if (ObjectUtils.isEmpty(articleConfigInDB)){
            //todo  这里需要考虑在哪里新增文章配置
            ArticleConfig articleConfig = new ArticleConfig();
            articleConfig.setId(IdUtil.getSnowflakeNextId());
            articleConfig.setArticleId(articleConfigDto.getArticleId());
            articleConfig.setIsComment(0);
            articleConfig.setIsForward(0);
            articleConfig.setIsDown(0);
            articleConfig.setIsDelete(0);
            int insert = articleConfigMapper.insert(articleConfig);
            if (insert==1){
                ArticleConfigVo articleConfigVo = new ArticleConfigVo();
                BeanUtil.copyProperties(articleConfig,articleConfigVo);
                return articleConfigVo;
            }
            throw new RuntimeException("数据新增出错");
        }
        ArticleConfigVo articleConfigVo = new ArticleConfigVo();
        BeanUtil.copyProperties(articleConfigInDB,articleConfigVo);
        return articleConfigVo;
    }

    private Integer getChannelId(String tag) {
        if("__all__".equals(tag)){
            return null;
        }

        if ("__dyna__".equals(tag)){
            //todo 目前不知道要做什么处
            return null;
        }

        return Integer.parseInt(tag);
    }
}
